#include<stdio.h>
#include<stdbool.h>
#define Size 3


//初始化函数 : 用于对操作对象的初始状态赋值
void InitBoard(char (*Board)[Size])
{
    for(int i = 0; i < Size; i++)
    {
        for(int j = 0; j < Size; j++)
        {
            Board[i][j] = ' ';   // 每个位置初始化为空格
        }
    }
}

//打印棋盘
void PrintBoard(char (*Board)[Size])
{
    for(int i = 0; i < Size; i++)
    {
        for(int j = 0; j < Size; j++)
        {
            printf("%c",Board[i][j]);
            if(j < Size - 1) 
                printf("  |");
        }
        printf("\n");
        if(i < Size -1) 
            printf("---|---|---\n");
    }
}

//下棋
bool MakeMove(char (*Board)[Size],int row, int col,char player)
{
    //非法位置
    if(row < 0 || row >= Size || col < 0 || col >= Size)
    {
        printf("下棋位置错误，请重新输入！");
        return false;
    }
    //下棋位置有棋子
    if(Board[row][col] != ' ')
    {
        printf("该位置已有棋子，请重新输入！");
        return false;
    }
    Board[row][col] = player;
    return true;

}

//判断是否获胜
bool CheckIsWin(char (*Board)[Size],char player)
{
    for(int i = 0; i < Size; i++)
    {
        if(Board[i][0] == player 
        && Board[i][1] == player 
        && Board[i][2] == player)
        return true;
    }

    for(int i = 0; i < Size; i++)
    {
        if(Board[0][i] == player 
        && Board[1][i] == player 
        && Board[2][i] == player)
        return true;
    }

    for(int i = 0; i < Size; i++)
    {
        if(Board[0][0] == player 
        && Board[1][1] == player 
        && Board[2][2] == player)
        return true;
    }

    for(int i = 0; i < Size; i++)
    {
        if(Board[0][2] == player 
        && Board[1][1] == player 
        && Board[2][0] == player)
        return true;
    }
    return false;
}


// 判平
bool CheckIsDraw(char (*Board)[Size])
{
    for(int i = 0; i < Size; i++)
    {
        for(int j = 0; j < Size; j++)
        {
            if(Board[i][j] == ' ')
                return false;
        }
    }
    return true;
}

int main()
{
    char Board[Size][Size] = {0};
    InitBoard(Board);

    char player = 'X';
    while(1)
    {
        PrintBoard(Board);
        int row = 0, col = 0;
        printf("请|%c|选手下棋",player);

        //从终端读取输入
        // 阻塞函数 ： 让程序进入等待状态，直到收到输入才会继续执行程序
        scanf("%d %d",&row,&col);
        if(MakeMove(Board,row,col,player) == false)
        {
            continue;
        }
        
        if(CheckIsWin(Board,player) == true)
        {
            PrintBoard(Board);
            printf("恭喜|%c|选手获胜！\n",player);
            break;
        }

        if(CheckIsDraw(Board))
        {
            PrintBoard(Board);
            printf("平局");
            break;
        }
        //换边
        player = (player == 'X') ? 'O' : 'X';
    }
    return 0;
}